package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.service.ICompanyService;
import redis.clients.jedis.Jedis;

public class CompanyServiceImpl implements ICompanyService {
    /**
     * 属于来源？
     * 因为首页的公司信息如果有大量人访问，数据直接冲数据库里面取会发生数据库崩溃
     * 所以，我们需要保证数据一致的情况下，在数据库查询一次，其他数据来源于redis
     * 1.判断redis里面是否有数据
     * 2.如果有，则取redis数据
     * 3.如果没有则取数据库数据
     *
     * @return
     */
    @Override
    public CompanyModel getCompanyModel() {
        CompanyModel companyModel = null;
        Jedis jedis = new Jedis();
        if (jedis.exists("logo")) {
            companyModel = new CompanyModel();
            companyModel.setLogo(jedis.get("logo"));
            companyModel.setPhone(jedis.get("phone"));
            companyModel.setNet(jedis.get("net"));
            companyModel.setEmail(jedis.get("email"));
            companyModel.setAddress(jedis.get("address"));
            companyModel.setVersion(jedis.get("version"));
            companyModel.setLinePhone(jedis.get("linePhone"));
            System.out.println("redis");
        } else {
            CompanyDao companyDao = new CompanyImpl();
            companyModel = companyDao.getCompanyModel();
//            jedis.set("logo", companyModel.getLogo());
//            int a=10/0;
//            jedis.expire("logo", 1000);
//            jedis.setex("logo",1000,companyModel.getLogo());
//            Jedis<String,String>
//            Jedis<Object,Object>
            jedis.set("phone", companyModel.getPhone());
            jedis.set("net", companyModel.getNet());
            jedis.set("email", companyModel.getEmail());
            jedis.set("address", companyModel.getAddress());
            jedis.set("version", companyModel.getVersion());
            jedis.set("linePHone", companyModel.getLinePhone());
            System.out.println("mysql");
        }
        return companyModel;
    }

    /**
     * 只要用到redis，记得在后台管理操作数据时成功，需要清空redis数据
     * 修改，删除，新增
     * @param companyModel
     * @return
     */
    public int update(CompanyModel companyModel) {
        CompanyDao companyDao = new CompanyImpl();
        int result = companyDao.update(companyModel);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("logo");
        }
        return result;
    }

    public static void main(String[] args) {
        new CompanyServiceImpl().getCompanyModel();
    }

}
